package com.yimo.chromedriver;

import com.yimo.common.util.HttpClient;
import lombok.Data;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import retrofit2.http.Url;
import sun.awt.OSInfo;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * create by jsm on 2018/11/7
 */
@Component
@Data
public class HunLiJi extends Crawler {
    private String url;
    @Value("${chromedriver.driver:/usr/local/bin/chromedriver}")
    private String driverPath;
    @Value("${chromedriver.savePath:/Users/yimouser/Documents}")
    private String savePath;
    ChromeDriver chromeDriver = null;
    Calendar calendar = Calendar.getInstance();
    @Resource
    private HttpClient httpClient;

    public ChromeDriver climb() throws IOException {
        Date now = new Date();
        calendar.setTime(now);
        String subFolder = savePath + "/hlj/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + now.getTime();
        File subFolderFile = new File(subFolder);
        if (subFolderFile.exists() == false) {
            subFolderFile.mkdirs();
        }
        if (chromeDriver == null) {
            chromeDriver = open();
        }else{
            chromeDriver.get(getUrl());
        }
        WebElement element = chromeDriver.findElement(By.className("rc-main"));
        System.out.println(element.getText());
        List <WebElement> imgs = element.findElements(By.tagName("img"));
        for (WebElement img : imgs) {
            String src = img.getAttribute("src");
            InputStream inputStream = httpClient.doGetStream(src);
            BufferedImage buffer = ImageIO.read(inputStream);
            ImageIO.write(buffer, "png", new File(subFolder + "/i" + new Date().getTime() + ".png"));
            System.out.println(src);
        }
        try {

            File contentFile = new File(subFolder + "/c" + new Date().getTime() + ".txt");
            FileOutputStream fw = new FileOutputStream(contentFile);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fw, "UTF-8"));
            bw.write(element.getText());
            bw.flush();
            bw.close();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return chromeDriver;
    }

}
